#!/usr/bin/env python

import os,cPickle,threading,sys

try:
    with open('/tmp/monitor-daemon.txt','r') as f:
        alldata = cPickle.load(f)
except:
    print '%s get params error,exit run: %s' % (__file__,__file__)
    sys.exit()

def runcmd(host,data):
    for project in data:
        filename = '/cihi/web/web/rrdtool/%s_%s.rrd' % (host,project)
        if project != 'get_time' and data[project].get('info').find('|') != -1:
            fields = []
            result = {}
            ds = ''
            ds_data = 'N'
            t,value = data[project]['info'].split('|')
            for x in value.split(';'):
                n,y,w = x.split(':')
                fields.append(n)
                result[n] = y
            for i in range(len(fields)):
                ds += 'DS:%s:GAUGE:120:U:U ' % fields[i]
                ds_data += ':%s' % result[fields[i]]
            createcmd="/usr/bin/rrdtool create %s \
-s 60 \
%s \
RRA:AVERAGE:0.5:1:480 \
RRA:AVERAGE:0.5:5:600 \
RRA:AVERAGE:0.5:30:700 \
RRA:AVERAGE:0.5:120:790 \
RRA:AVERAGE:0.5:1440:797 \
RRA:MAX:0.5:1:480 \
RRA:MAX:0.5:5:600 \
RRA:MAX:0.5:30:700 \
RRA:MAX:0.5:120:790 \
RRA:MAX:0.5:1440:797 \
RRA:MIN:0.5:1:480 \
RRA:MIN:0.5:5:600 \
RRA:MIN:0.5:30:700 \
RRA:MIN:0.5:120:790 \
RRA:MIN:0.5:1440:797" % (filename,ds)
            if not os.path.isfile(filename):
                os.system('rm -rf %s && %s' % (filename,createcmd))
            os.system('/usr/bin/rrdtool update %s %s' % (filename,ds_data))

threads = []
for host in alldata:
    threads.append(threading.Thread(target=runcmd,args=(host,alldata[host])))
for t in threads:
    t.start()
